import React, { useState, useRef, useEffect } from 'react';
import { Tree } from 'antd';
import type { TreeProps } from 'antd';
import './ReportTreeSection.less';

interface ReportTreeSectionProps {
  title?: string;
  treeData: any[];
  selectedKeys?: string[];
  expandedKeys?: string[];
  onSelect?: TreeProps['onSelect'];
  onExpand?: TreeProps['onExpand'];
  onContextMenuAction?: (action: string, node: any) => void;
  className?: string;
}

const ReportTreeSection: React.FC<ReportTreeSectionProps> = ({
  title,
  treeData,
  selectedKeys = [],
  expandedKeys = [],
  onSelect,
  onExpand,
  onContextMenuAction,
  className,
}) => {
  const [contextMenuVisible, setContextMenuVisible] = useState(false);
  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
  const [rightClickedNode, setRightClickedNode] = useState<any>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  // 处理右键点击
  const handleRightClick = ({ event, node }: any) => {
    event.preventDefault();
    setRightClickedNode(node);
    setContextMenuPosition({
      x: event.clientX,
      y: event.clientY,
    });
    setContextMenuVisible(true);
  };

  // 处理菜单项点击
  const handleMenuClick = (key: string) => {
    if (onContextMenuAction && rightClickedNode) {
      onContextMenuAction(key, rightClickedNode);
    }
    setContextMenuVisible(false);
  };

  // 处理点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setContextMenuVisible(false);
      }
    };

    if (contextMenuVisible) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [contextMenuVisible]);

  return (
    <div className={`report-tree-section-container ${className || ''}`}>
      <Tree
        className="report-custom-tree"
        showIcon
        showLine={{ showLeafIcon: false }}
        selectedKeys={selectedKeys}
        expandedKeys={expandedKeys}
        onSelect={onSelect}
        onExpand={onExpand}
        onRightClick={handleRightClick}
        treeData={treeData}
      />
      
      {/* 自定义定位的右键菜单 */}
      {contextMenuVisible && (
        <div
          ref={menuRef}
          className="report-tree-context-menu"
          style={{
            left: contextMenuPosition.x,
            top: contextMenuPosition.y,
          }}
        >
          <div
            className="menu-item"
            onClick={() => handleMenuClick('report')}
          >
            查看填报内容
          </div>
          <div
            className="menu-item"
            onClick={() => handleMenuClick('edit')}
          >
            编辑填报内容
          </div>
        </div>
      )}
    </div>
  );
};

export default ReportTreeSection;